const jwt = require('jsonwebtoken');

const errorType = require('../constants/error-type');
const userService = require('../service/user.service');
const md5Password = require('../util/password-handle');
const { PUBLIC_KEY } = require('../app/config');
const authService = require('../service/auth.service');

const verifyLogin = async (ctx, next) => {
  // 1. 获取帐号密码
  const { name, password } = ctx.request.body;
  // 2. 判断帐号和密码是否为空
  if (!name || !password) {
    const error = new Error(errorType.NAME_OR_PASSWORD_IS_REQUIRED);
    return ctx.app.emit('error', error, ctx);
  }
  // 3. 判断用户是否存在
  const result = await userService.getUserByName(name);
  const user = result[0];
  if (!user) {
    const error = new Error(errorType.USER_DOES_NOT_EXISTS);
    return ctx.app.emit('error', error, ctx);
  }
  // 4.判断密码是否一致
  // ctx.request.body = result[0]
  if (md5Password(password) !== user.password) {
    const error = new Error(errorType.PASSWORD_IS_INCORRENT);
    return ctx.app.emit('error', error, ctx);
  }
  ctx.user = user;
  await next();
}

const verifyAuth = async (ctx, next) => {
  console.log("验证登录授权的moddleware   verifyAuth");
  const authorization = ctx.headers.authorization;
  if (!authorization) {
    const error = new Error(errorType.UNAUTHORIZATION);
    return ctx.app.emit('error', error, ctx);
  }
  const token = authorization.replace("Bearer ", "");
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ["RS256"]
    });
    ctx.user = result;
    await next();
  } catch(err) {
    const error = new Error(errorType.UNAUTHORIZATION);
    ctx.app.emit('error', error, ctx);
  }
}
/* 
  1. 很多内容都需要验证权限: 修改/删除动态 修改/删除评论
  2. 接口: 业务接口系统 / 后台管理系统
  一对一: user -> role
  多对多: role -> menu(删除/修改动态)
*/
const verifyPermission =  async (ctx, next) => {
  console.log("验证权限授权的moddleware   verifyPermission");
  console.log(ctx.user);
  const [resourceKey] = Object.keys(ctx.params);
  const tableName = resourceKey.replace('Id', '');
  const resourceId = ctx.params[resourceKey];
  const { id } = ctx.user;
  try {
    const isPermission = await authService.checkResource(tableName, resourceId, id);
    if (!isPermission) throw new Error();
    await next();
  } catch (err) {
    const error = new Error(errorType.UNPERMISSION)
    ctx.app.emit('error', error, ctx);
  }
}

// 闭包获取类型
/* const verifyPermission = (tableName) => {
  return async (ctx, next) => {
    console.log("验证权限授权的moddleware   verifyPermission");
    const { id } = ctx.user;
    const { momentId } = ctx.params;
    try {
      const isPermission = await authService.checkResource(tableName, momentId, id);
      if (!isPermission) throw new Error();
      await next();
    } catch (err) {
      const error = new Error(errorType.UNPERMISSION)
      ctx.app.emit('error', error, ctx);
    }
  }
} */

module.exports = {
  verifyLogin,
  verifyAuth,
  verifyPermission
}
